<script lang="ts" setup>
import type {
  SliderMode,
  SliderOrientation,
  SliderSize,
} from '@fluentui/web-components';

import { nextTick, onMounted, ref } from 'vue';

withDefaults(
  defineProps<{
    disabled?: boolean;
    max?: number | string;
    min?: number | string;
    mode?: SliderMode;
    name?: string;
    orientation?: SliderOrientation;
    required?: boolean;
    size?: SliderSize;
    step?: number | string;
  }>(),
  {
    disabled: false,
    min: 0,
    max: 100,
    step: undefined,
    orientation: 'horizontal',
    mode: 'single-value',
    size: 'medium',
    required: false,
    name: undefined,
  },
);

const emit = defineEmits<{
  change: [event: Event];
}>();

// Define the model with 'value' as argument
const value = defineModel<number | string>({ default: 0 });

const handleChange = (event: Event) => {
  const target = event.target as HTMLInputElement;
  emit('change', event);
  // Update the model directly instead of emitting an event
  value.value = target.value;
};

const slider = ref<HTMLInputElement>();

onMounted(() => {
  nextTick(() => {
    if (slider.value) {
      // Set the initial value from the model
      slider.value.value = value.value.toString();
    }
  });
});
</script>

<template>
  <fluent-slider
    ref="slider"
    :disabled="disabled"
    :min="min?.toString()"
    :max="max?.toString()"
    :step="step?.toString()"
    :orientation="orientation"
    :mode="mode"
    :size="size"
    :value="value?.toString()"
    :name="name"
    :required="required"
    @change="handleChange"
  >
    <slot></slot>
  </fluent-slider>
</template>

<style scoped></style>
